package com.zzz.robot201.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.zzz.robot201.R;
import com.zzz.robot201.app.base.BaseViewActivity;
import com.zzz.robot201.app.config.AppContent;
import com.zzz.robot201.di.component.DaggerHomeComponent;
import com.zzz.robot201.mvp.contract.HomeContract;
import com.zzz.robot201.mvp.presenter.HomePresenter;
import com.zzz.robot201.service.api.RobotUdpUtil;
import com.zzz.robot201.service.client.ResponseMsg;
import com.zzz.robot201.service.client.SendMsg;
import com.zzz.robot201.utils.SpUtils;
import com.zzz.robot201.utils.ToastUtil;

import org.lzh.framework.updatepluginlib.UpdateBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.provider.Telephony.Mms.Part.FILENAME;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.zzz.robot201.mvp.ui.activity.MsgFeedbackActivity.responseMsg;


public class HomeActivity extends BaseViewActivity<HomePresenter> implements HomeContract.View {

    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.iv_set)
    ImageView ivSet;
    @BindView(R.id.btn_home)
    Button btnHome;
    @BindView(R.id.tv_to_devices)
    TextView tvToDevices;
    float up = 0;
    float left = 0;
    byte unsigned_char_byte15_0 = 0;// byte[0] = 当前步态序号
    byte unsigned_char_byte15_4 = 13;// byte[4] = 当前状态序号
    float zx_speed = 0f;//转向速度
    private static String robotHost;
    private static int robotPort;
    private String deviceCode ;
    private Timer timer;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
            }
        }).start();
        return R.layout.activity_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        UpdateBuilder.create().check();
        deviceCode = (String) SpUtils.get(HomeActivity.this, AppContent.SaveInfoKey.DEVICECODE, "");


        new Thread(new Runnable() {
            @Override
            public void run() {
                receiveMsg(deviceCode, 43795);
            }
        }).start();

        timer=new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                Message message=new Message();
                message.what=1;
                handler.sendMessage(message);

            }
        }, 1000,3000);

    }

    private Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    updateUi();
                    break;

                default:
                    break;
            }
        };
    };
    private void updateUi() {
        if (responseMsg!=null) {

            //未找到传感器状态，暂只判断了 陀螺状态
            if (responseMsg.imu_state_char == 0) {
                tvToDevices.setText("正常");
                tvToDevices.setTextColor(getResources().getColor(R.color.green));
            } else{
                tvToDevices.setText("异常");
                tvToDevices.setTextColor(getResources().getColor(R.color.red));
            }

        }
    }
    private void sendUp(float up, float left, float zx, byte unsigned_0, byte unsigned_4) {
        robotHost = (String) SpUtils.get(HomeActivity.this, AppContent.SaveInfoKey.DEVICEIP, "");
        robotPort = (int) SpUtils.get(HomeActivity.this, AppContent.SaveInfoKey.DEVICEPORT, 1);
        RobotUdpUtil udp = new RobotUdpUtil();
        int test = 0;
        if (test == 0) {// 发起通信
            long[] unsigned_long_long = new long[]{0, 0};//时间，暂时都设为0;
            float[] float3 = new float[]{left, up, zx};// 顺序为x方向速度,y方向速度,转向速度
            float[] float2 = new float[]{0f, 0f};// 固定 0,0

            SendMsg sendMsg = new SendMsg(robotHost, robotPort, unsigned_long_long[0], unsigned_long_long[1])
                    .setFloat3(float3).setFloat2(float2)
                    .setUnsigned_char_byte15_0(unsigned_0)
                    .setUnsigned_char_byte15_4(unsigned_4)
                    .checkBuf();
            sendMsg(sendMsg);
        } else {
            // 接收通信
//            receiveMsg();
            udp.receiveMsg("00000001", 43795);
        }
    }


    DatagramSocket ds = null;

    private boolean sendMsg(SendMsg sendMsg) {
        boolean result = false;
        try {
            ds = new DatagramSocket();
            byte[] data = sendMsg.getbuf();

            DatagramPacket dp = new DatagramPacket(data, data.length,
                    InetAddress.getByName(sendMsg.getServerHost()),
                    sendMsg.getServerPort());
            ds.send(dp);
            result = true;
            System.out.println("发送：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
            return result;
        }
    }

    public static ResponseMsg responseMsg;

    public void receiveMsg(String deviceCode, int localPort) {
        boolean result = false;
        try {
            ds = new DatagramSocket(localPort);
            while (true) {
                byte[] buffer = new byte[260];
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                ds.receive(dp);
                buffer = dp.getData();
                responseMsg = ResponseMsg.getResponseMsg(buffer);

                InetAddress address = dp.getAddress();
                int port = dp.getPort();
                responseMsg.setHostIp(address.getHostAddress());
                responseMsg.setHostPort(port);
                responseMsg.setNowtime(new Date().getTime());
                responseMsg.setDeviceCode(deviceCode);
                System.out.println(responseMsg);
                write(responseMsg.toString());
//                Log.d("更新ui","55555");
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String DIR="robot";
    private void write(String content) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) { // 如果sdcard存在
            File file = new File(Environment.getExternalStorageDirectory()
                    .toString()
                    + File.separator
                    + DIR
                    + File.separator
                    + FILENAME); // 定义File类对象
            if (!file.getParentFile().exists()) { // 父文件夹不存在
                file.getParentFile().mkdirs(); // 创建文件夹
            }
            PrintStream out = null; // 打印流对象用于输出
            try {
                out = new PrintStream(new FileOutputStream(file, true)); // 追加文件
                out.println(content);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close(); // 关闭打印流
                }
            }
        } else { // SDCard不存在，使用Toast提示用户
            Toast.makeText(this, "保存失败，SD卡不存在！", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showLoading() {
        showBaseLoading();
    }

    @Override
    public void hideLoading() {
        hideBaseLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastUtil.showToast(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_msg, R.id.iv_set, R.id.btn_home,R.id.tv_to_devices})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_msg:
                launchActivity(new Intent(this, MsgActivity.class));
                break;
            case R.id.iv_set:
                launchActivity(new Intent(this, SetActivity.class));
                break;
            case R.id.btn_home:
                launchActivity(new Intent(this, MachineStatusActivity.class));
                break;
            case R.id.tv_to_devices:
                launchActivity(new Intent(this, EquipmentActivity.class));
                break;
        }
    }

    @OnClick()
    public void onViewClicked() {
    }
}
